package servlet;

import cn.school.dao.SubjectMapper;
import cn.school.entity.Subject;
import cn.school.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/addSubjectServlet")
public class AddSubjectServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String name=request.getParameter("subjectname");
        String gradeid=request.getParameter("gradeid");
        String classhour=request.getParameter("classhour");
        long gid=Long.parseLong(gradeid);
        int hour=Integer.parseInt(classhour);
        Subject subject=new Subject();
        subject.setSubjectname(name);
        subject.setClasshour(hour);
        subject.setGradeId(gid);
        //保存到数据库中。。。
        response.setContentType("text/html;charset=utf-8");//中文乱码问题解决
        PrintWriter out = response.getWriter();
        out.print("您刚才输入的课程信息是："+subject);
        SqlSession session = MybatisUtil.get();
        int add=0;
        try {
            SubjectMapper subjectMapper = session.getMapper(SubjectMapper.class);
            add = subjectMapper.add(subject);//异常
        }finally {
            MybatisUtil.close(session);
        }
        if(add>0)
        {   //重定向
            response.sendRedirect("subjects.jsp");
            //out.print("保存新课成功");
        }
        else{
            //  out.print("保存失败！");
            //转发
            request.getRequestDispatcher("/addsubject.jsp").forward(request,response);
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
